const db = require("../models");
const logger = require("../utils/utils.logger");
const {
  aes
} = require("../utils/utils.crypto");
const DAO = require("../dao/DAO");
const {
  forEach,
  indexOf
} = require("lodash");
const Daily = db.daily;
const Shop = db.shop;
const Op = db.Op;

// Daily.hasOne(Roles, {foreignKey: 'id', sourceKey: 'roleId'});
// Roles.belongsTo(Daily, {foreignKey: 'id', sourceKey: 'roleId'});

// Create and Save a new dailyData
exports.create = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!req.body.dayDate)
    return res.sendResult({
      data: "",
      code: 605,
      message: "日期不能为空！"
    });

  if (!req.body.dayIncomeMoney && req.body.dayIncomeMoney != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日收入现金不能为空！",
    });

  if (!req.body.dayIncomeWechat && req.body.dayIncomeWechat != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日收入微信不能为空！",
    });

  if (!req.body.dayIncomeAlipay && req.body.dayIncomeAlipay != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日收入支付宝不能为空！",
    });

  if (!req.body.dayIncomeAllMoney && req.body.dayIncomeAllMoney != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日收入合计不能为空！",
    });

  if (!req.body.dayBalanceMoney && req.body.dayBalanceMoney != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日现金余额不能为空！",
    });

  if (!req.body.dayBalanceWechat && req.body.dayBalanceWechat != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日微信余额不能为空！",
    });

  if (!req.body.dayBalanceAlipay && req.body.dayBalanceAlipay != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日支付宝余额不能为空！",
    });

  // if (!req.body.dayBalancePaymentCode)
  //   return res.sendResult({
  //     data: "",
  //     code: 605,
  //     message: "当日收款码余额不能为空！",
  //   });

  if (!req.body.dayBalanceAllMoney)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日合计余额不能为空！",
    });

  if (!req.body.dayIncomePaymentCode && req.body.dayIncomePaymentCode != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日收入收款码不能为空！",
    });

  if (!req.body.sportVoteCashPrize && req.body.sportVoteCashPrize != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩彩票兑奖不能为空！",
    });

  if (!req.body.sportScratchCardCashAPrize && req.body.sportScratchCardCashAPrize != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩刮刮卡兑奖不能为空！",
    });

  if (!req.body.luckyLotteryRedemption && req.body.luckyLotteryRedemption != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "福彩兑奖不能为空！",
    });

  if (!req.body.sportPayables && req.body.sportPayables != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩应交款不能为空！",
    });

  if (!req.body.luckyPayables && req.body.luckyPayables != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "福彩应交款不能为空！",
    });

  if (!req.body.scratchCardPayables && req.body.scratchCardPayables != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "刮刮卡应交款不能为空！",
    });

  if (!req.body.totalPayables && req.body.totalPayables != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "应交款合计不能为空！",
    });

  if (!req.body.sportAtThatTime && req.body.sportAtThatTime != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩机当日余额不能为空！",
    });

  if (!req.body.luckyAtThatTime && req.body.luckyAtThatTime != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "福彩机当日余额不能为空！",
    });

  if (!req.body.scratchCardAtThatTime && req.body.scratchCardAtThatTime != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "刮刮卡当日余额不能为空！",
    });

  if (!req.body.totalAtThatTime && req.body.totalAtThatTime != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日余额汇总不能为空！",
    });

  if (!req.body.sportRechargeAmount && req.body.sportRechargeAmount != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩充值金额不能为空！",
    });

  if (!req.body.luckyRechargeAmount && req.body.luckyRechargeAmount != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "福彩充值金额不能为空！",
    });

  if (!req.body.sportCardSubscriptionAmount && req.body.sportCardSubscriptionAmount != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩订卡金额不能为空！",
    });

  if (!req.body.luckyCardSubscriptionAmount && req.body.luckyCardSubscriptionAmount != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "福彩订卡金额不能为空！",
    });

  if (!req.body.sportsLotteryCommission && req.body.sportsLotteryCommission != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "体彩佣金不能为空！",
    });

  if (!req.body.luckyLotteryCommission && req.body.luckyLotteryCommission != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "福彩佣金不能为空！",
    });

  if (!req.body.cashWithdrawalAmountOf100 && req.body.cashWithdrawalAmountOf100 != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "百元现金取走量不能为空！",
    });

  if ((req.body.cashWithdrawalAmountOf100 && req.body.cashWithdrawalAmountOf100 !== 0) && !req.body.takeAwayPeople)
    return res.sendResult({
      data: "",
      code: 605,
      message: "取走人不能为空！"
    });

  if (!req.body.presenter)
    return res.sendResult({
      data: "",
      code: 605,
      message: "提交人不能为空！"
    });

  // if (!req.body.substitutePersonnel)
  //   return res.sendResult({
  //     data: "",
  //     code: 605,
  //     message: "替班人员不能为空！",
  //   });

  if (!req.body.shop)
    return res.sendResult({
      data: "",
      code: 605,
      message: "店铺不能为空！"
    });

  if (!req.body.difference)
    return res.sendResult({
      data: "",
      code: 605,
      message: "差异不能为空！"
    });
  if (!req.body.dailyIncomeScrapingCard && req.body.dailyIncomeScrapingCard != 0)
    return res.sendResult({
      data: "",
      code: 605,
      message: "当日收入刮刮卡不能为空！"
    });

  // Create a dailyData
  const dailyData = {
    dayDate: req.body.dayDate,
    dayIncomeMoney: req.body.dayIncomeMoney,
    dayIncomeWechat: req.body.dayIncomeWechat,
    dayIncomeAlipay: req.body.dayIncomeAlipay,
    dayIncomeAllMoney: req.body.dayIncomeAllMoney,
    dayBalanceMoney: req.body.dayBalanceMoney,
    dayBalanceWechat: req.body.dayBalanceWechat,
    dayBalanceAlipay: req.body.dayBalanceAlipay,
    dayBalancePaymentCode: req.body.dayBalancePaymentCode,
    dayBalanceAllMoney: req.body.dayBalanceAllMoney,
    dayIncomePaymentCode: req.body.dayIncomePaymentCode,
    sportVoteCashPrize: req.body.sportVoteCashPrize,
    sportScratchCardCashAPrize: req.body.sportScratchCardCashAPrize,
    luckyLotteryRedemption: req.body.luckyLotteryRedemption,
    sportPayables: req.body.sportPayables,
    luckyPayables: req.body.luckyPayables,
    scratchCardPayables: req.body.scratchCardPayables,
    totalPayables: req.body.totalPayables,
    sportAtThatTime: req.body.sportAtThatTime,
    luckyAtThatTime: req.body.luckyAtThatTime,
    scratchCardAtThatTime: req.body.scratchCardAtThatTime,
    totalAtThatTime: req.body.totalAtThatTime,
    sportRechargeAmount: req.body.sportRechargeAmount,
    luckyRechargeAmount: req.body.luckyRechargeAmount,
    sportCardSubscriptionAmount: req.body.sportCardSubscriptionAmount,
    luckyCardSubscriptionAmount: req.body.luckyCardSubscriptionAmount,
    sportsLotteryCommission: req.body.sportsLotteryCommission,
    luckyLotteryCommission: req.body.luckyLotteryCommission,
    cashWithdrawalAmountOf100: req.body.cashWithdrawalAmountOf100,
    takeAwayPeople: req.body.takeAwayPeople,
    presenter: req.body.presenter,
    substitutePersonnel: req.body.substitutePersonnel,
    shop: req.body.shop,
    difference: req.body.difference,
    state: req.body.state || true,
    notes: req.body.notes,
    dailyIncomeScrapingCard: req.body.dailyIncomeScrapingCard,
    alipayRecharge: req.body.alipayRecharge,
    weChatRecharge: req.body.weChatRecharge,
    dailyOutScrapingCard: req.body.dailyOutScrapingCard,
    redemptionAllMoney: req.body.redemptionAllMoney,
    scrapingCardCommission: req.body.scrapingCardCommission,
    nextDailyOutScrapingCard: req.body.nextDailyOutScrapingCard
  };

  Daily.findOne({
      where: {
        dayDate: pm.dayDate,
        shop: pm.shop
      }
    })
    .then((singleUser) => {
      if (singleUser && singleUser.id)
        return res.sendResultAto(null, 605, "已存在！");
      DAO.create(Daily, dailyData, (data) => {
        logger.debug(
          `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
            pm
          )}; 响应：${JSON.stringify(data)}`
        );
        res.sendResult(data);
      });
    })
    .catch((resError) => {
      console.log("resError", resError);
      // return res.sendResult({ data: "", code: 605, message: "ID不能为空！" });
    });
};

// Retrieve all user from the database.
exports.findAll = (req, res) => {
  const pm = req.body;

  pm.params.dayDate ?
    (pm.params.dayDate = {
      [Op.substring]: `%${pm.params.dayDate}%`,
    }) :
    (pm.params.dayDate = "");

  pm.params.shop ?
    (pm.params.shop = {
      [Op.substring]: `%${pm.params.shop}%`,
    }) :
    (pm.params.shop = "");

  DAO.list(Daily, pm, (list) => {
    res.sendResult(list);
  });
};

// Find a single Daily with an id
exports.findOne = (req, res) => {
  const pm = req.body;
  DAO.findOne(Daily, pm, (data) => {
    res.sendResult(data);
  });
};

// Update a Daily by the id in the request
exports.update = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id)
    return res.sendResult({
      data: "",
      code: 605,
      message: "ID不能为空！"
    });
  DAO.update(Daily, pm, {
    id: pm.id
  }, (data) => {
    res.sendResult(data);
  });
};
// Update a Daily by the id in the request
exports.reset = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id)
    return res.sendResult({
      data: "",
      code: 605,
      message: "ID不能为空！"
    });
  if (!pm.password)
    return res.sendResult({
      data: "",
      code: 605,
      message: "password不能为空！",
    });
  Daily.update({
      password: pm.password
    }, {
      where: {
        id: pm.id,
      },
    })
    .then((uD) => {
      res.status(200).sendResultAto(uD, 200, "重置密码成功");
    })
    .catch((err) => {
      console.log(err);
      res.status(500).sendResultAto(err, 605, "重置错误");
    });
};
// Delete a Daily with the specified id in the request
exports.delete = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id)
    return res.sendResult({
      data: "",
      code: 605,
      message: "ID不能为空！"
    });
  DAO.delete(Daily, {
    id: pm.id
  }, (data) => {
    res.sendResult(data);
  });
};

// Delete all Daily from the database.
exports.deleteAll = (req, res) => {
  const pm = req.body;
  DAO.deleteAll(Daily, (data) => {
    res.sendResult(data);
  });
};

// Delete Daily from the database.
exports.query = (req, res) => {
  const pm = req.body;
  let sql = "SELECT * FROM `daily`";
  DAO.doQuery(sql, (data) => {
    res.sendResult(data);
  });
};

// 销售日报表
exports.monthAll = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT id, dayDate, sportPayables, luckyPayables, scratchCardPayables, totalPayables,dayIncomePaymentCode, shop FROM `dailies` WHERE  " + pm.startTime + " <= `dayDate` && `dayDate` <= " + pm.endTime + "ORDER BY shop ASC";
  // console.log('asasasasasasasasasassas', sql)

  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部

  })
}

// 押款日报表
exports.moneyAll = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT id, dayDate, dayBalanceMoney, dayBalanceWechat, dayBalanceAlipay, dayBalancePaymentCode,dayBalanceAllMoney,sportAtThatTime,luckyAtThatTime,scratchCardAtThatTime,totalAtThatTime, shop, sportAtThatTime + luckyAtThatTime + dayBalanceMoney + dayBalanceWechat + dayBalanceAlipay + dayBalancePaymentCode + scratchCardAtThatTime  AS subtotalOfDeposit FROM `dailies` WHERE  " + pm.startTime + " <= `dayDate` && `dayDate` <= " + pm.endTime + "ORDER BY shop ASC";
  // console.log('asasasasasasasasasassas', sql)

  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })

}

// 销售总额
exports.totalMonth = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT dayDate, SUM(totalPayables) AS totalValue FROM `dailies` where " + pm.startTime + " <= `dayDate` && `dayDate` <= " + pm.endTime + "GROUP BY dayDate "
  // SELECT SUM(totalPayables) AS totalValue FROM `dailies` WHERE dayDate >= '2023-10-01' AND dayDate <= '2023-10-31' 27237
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}

// 店内各项销售占比
exports.monthProportion = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT shop, dayDate, SUM(sportPayables) AS sportPayablesTotal, SUM(luckyPayables) AS luckyPayablesTotal, SUM(scratchCardPayables) AS scratchCardPayablesTotal, SUM(totalPayables) AS totalPayablesTotal,SUM(dayIncomePaymentCode) AS dayIncomePaymentCodeTotal,SUM(totalPayables) AS total_count,(SUM(sportPayables) / SUM(totalPayables)) * 100 AS sportPayablesProportion,(SUM(dayIncomePaymentCode) / SUM(totalPayables)) * 100 AS dayIncomePaymentCodeProportion,(SUM(luckyPayables) / SUM(totalPayables)) * 100 AS luckyPayablesProportion,(SUM(scratchCardPayables) / SUM(totalPayables)) * 100 AS scratchCardPayablesProportion FROM `dailies` WHERE dayDate >=" + pm.startTime + "  AND dayDate <= " + pm.endTime + "GROUP BY shop ";
  // SELECT shop, SUM(totalPayables) AS sum_field, COUNT(shop) AS total_count,    (SUM(totalPayables) / (SELECT SUM(totalPayables) AS totalValue FROM `dailies` WHERE dayDate >= "+ pm.startTime +" AND dayDate <= " + pm.endTime + ")) * 100 AS field_percentage  FROM `dailies`  WHERE dayDate >= "+ pm.startTime +" AND dayDate <= " + pm.endTime + "  GROUP BY shop"
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}

// 各店销售占比
exports.eachStoreProportion = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT shop, SUM(totalPayables) AS sum_field, COUNT(shop) AS total_count, (SUM(totalPayables) / (SELECT SUM(totalPayables) AS totalValue FROM `dailies` WHERE dayDate >= " + pm.startTime + " AND dayDate <= " + pm.endTime + ")) * 100 AS field_percentage  FROM `dailies`  WHERE dayDate >= " + pm.startTime + " AND dayDate <= " + pm.endTime + "  GROUP BY shop"
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}


// 压款 总额
exports.press = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT dayDate, SUM(sportAtThatTime + luckyAtThatTime + dayBalanceMoney + dayBalanceWechat + dayBalanceAlipay + dayBalancePaymentCode + scratchCardAtThatTime) AS totalNumber, SUM(scratchCardAtThatTime) AS scratchCard,SUM(scratchCardAtThatTime) / SUM(sportAtThatTime + luckyAtThatTime + dayBalanceMoney + dayBalanceWechat + dayBalanceAlipay + dayBalancePaymentCode + scratchCardAtThatTime) * 100 AS Proportion FROM `dailies` WHERE " + pm.startTime + " <= dayDate AND dayDate <= " + pm.endTime + " GROUP BY dayDate"
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}



// 验证当前d店铺日期是否提交过
exports.thisdaysend = async (req, res) => {
  const pm = req.body;
  Daily.findOne({
      where: {
        dayDate: pm.dayDate,
        shop: pm.shop
      }
    })
    .then((singleUser) => {
      if (singleUser && singleUser.id) {
        return res.sendResult({
          data: singleUser,
          code: 200,
          message: "已存在！"
        });
      } else {
        return res.sendResult({
          data: null,
          code: 200,
          message: "该日期未提交"
        });
      }
    })
}


// 当前时间以前最近一天有数据的
exports.lastDayData = async (req, res) => {
  const pm = req.body;
  // DATE(NOW())
  let sql = "SELECT * FROM `dailies` WHERE dayDate < " + pm.dayDate + " and shop = " + pm.shop + " ORDER BY dayDate DESC LIMIT 1"
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}


// 刮刮卡记录（安天 各店）
exports.scrapingCardRecord = async (req, res) => {
  const pm = req.body;
  // DATE(NOW())
  let sql = "SELECT id, dayDate, nextDailyOutScrapingCard, dailyOutScrapingCard, dailyIncomeScrapingCard, shop FROM `dailies` WHERE  " + pm.startTime + " <= `dayDate` && `dayDate` <= " + pm.endTime + "ORDER BY shop ASC";
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}

// 刮刮卡记录 每天的
exports.scrapingCardRecordDay = async (req, res) => {
  const pm = req.body;
  // DATE(NOW())
  let sql = "SELECT dayDate,dailyIncomeScrapingCard, nextDailyOutScrapingCard, dailyOutScrapingCard, SUM(dailyIncomeScrapingCard - nextDailyOutScrapingCard - dailyOutScrapingCard) AS totalValue FROM `dailies` where " + pm.startTime + " <= `dayDate` && `dayDate` <= " + pm.endTime + "GROUP BY dayDate "
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}


// 刮刮卡记录 不同店铺合计值
exports.scrapingCardRecordTotal = async (req, res) => {
  const pm = req.body;
  let sql = "SELECT shop, dayDate, SUM(dailyIncomeScrapingCard) AS dailyIncomeScrapingCardTotal, SUM(nextDailyOutScrapingCard) AS nextDailyOutScrapingCardTotal, SUM(dailyOutScrapingCard) AS dailyOutScrapingCardTotal  FROM `dailies` WHERE dayDate >=" + pm.startTime + "  AND dayDate <= " + pm.endTime + "GROUP BY shop ";
  await DAO.doQuery(sql, (data) => {
    var dataItem = {
      data: data.data[0],
      code: 200,
      message: '查询成功！'
    }
    res.sendResult(dataItem); // 输出全部
  })
}